import random

from django import http
from django.views import View
from django_redis import get_redis_connection

from apps.verifications import constants
from utils.response_code import RETCODE


class SMSCodeView(View):
    def get(self,request,mobile):
        image_code = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')
        image_client = get_redis_connection('verify_image_code')
        redis_img_code = image_client.get('img_%s' % uuid)
        if not redis_img_code:
            return http.JsonResponse({'code': "4001", 'errmsg': '图形验证码失效了'})
        image_client.delete('img_%s' % uuid)
        print('前端',image_code.lower())
        print(redis_img_code.decode().lower())
        if image_code.lower() != redis_img_code.decode().lower():
            return http.JsonResponse({'code': "4001", 'errmsg': '输入图形验证码有误'})
        sms_code = "%06d"% random.randint(0,999999)
        redis_sms_client = get_redis_connection('sms_code')
        send_flag = redis_sms_client.get('send_flag_%s' % mobile)
        if send_flag:
            return http.JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '发送短信过于频繁'})

        # 创建管道
        p1 = redis_sms_client.pipeline()

        # 短信验证码的发送
        # 用管道代替
        p1.setex('sms_%s' %mobile, 300,sms_code)
        p1.setex('send_flag_%s' % mobile, 60, 1)
        # redis_sms_client.setex('sms_%s' %mobile, 300,sms_code)
        # redis_sms_client.setex('send_flag_%s' % mobile, 60, 1)
        from celery_tasks.sms.tasks import send_sms_code_ccp
        send_sms_code_ccp.delay(mobile,sms_code)
        print("原始文件的短信码", sms_code)
        # 管道的执行
        p1.execute()

        return http.JsonResponse({'code': "0", 'errmsg': '发送短信成功'})


class ImageCodeView(View):
    """图形验证码"""

    def get(self, request, uuid):
        """
        :param request: 请求对象
        :param uuid: 唯一标识图形验证码所属于的用户
        :return: image/jpg
        """
        from libs.captcha.captcha import captcha
        text,image_code = captcha.generate_captcha()

        image_client = get_redis_connection('verify_image_code')
        # image_client.setex('img_%s' % uuid,text,max_age=300)
        image_client.setex('img_%s' % uuid, constants.IMAGE_CODE_REDIS_EXPIRES,text)
        return http.HttpResponse(image_code, content_type='image/jpg')
        # pass